package com.kgcx.order.rabbitmq;

import com.alibaba.fastjson.JSONObject;
import com.kgcx.common.client.coupon.CouponClient;
import com.kgcx.common.client.coupon.pojo.Coupon;
import com.kgcx.common.eum.OrderEnum;
import com.kgcx.common.log.Log;
import com.kgcx.core.utils.JsonUtil;
import com.kgcx.order.domain.Order;
import com.kgcx.order.domain.PriceActualPrice;
import com.kgcx.order.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;

@Component

public class UpdateListener {

    private static final Logger LOG = LoggerFactory.getLogger(UpdateListener.class);

    @Autowired
    private StringRedisTemplate strRedisTemplate;
    @Autowired
    private OrderService service;
    @Autowired
    private CouponClient couponClient;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RabbitListener(queues = "kgcxOrderPriceUpdateQueue", errorHandler = "custRabbitListenerErrorHandler")
    public void processOrderStatus(String json) {

        LOG.info("订单 - 状态变更：json=" + json);
        JSONObject jsonObject = JSONObject.parseObject(json);
        //获取并解析消息
        PriceActualPrice pap = JsonUtil.toObject(jsonObject.getJSONObject("body").toJSONString(), PriceActualPrice.class);
//        计算完价格暂时不需要更改订单状态为待支付
//        strRedisTemplate.opsForHash()
//                .put(OrderEnum.ORDERS_STATUS, pap.getOrderId(),
//                        String.valueOf(OrderEnum.PENDING_PAY));

        Order order = service.getIngOrderByOrderNo(pap.getOrderId());

        if (order != null) {
            // 1.redis.ORDERS_ING 中更新价格(含优惠券的价格)、里程、优惠券信息
            order.setFactPrice(pap.getTotalMoney() == null ? null : pap.getTotalMoney().intValue());
            order.setFactFinalPrice(pap.getTotalFee() == null ? null : pap.getTotalFee().intValue());
            order.setDriveMile(pap.getMileage() == null ? null : pap.getMileage().intValue());
            if (pap.getCouponId() != null) {
                order.setCouponId(pap.getCouponId().intValue());
                couponClient.updateCouponState(pap.getCouponId(), Coupon.STATE_USING);
            }
            order.setDriveTime(pap.getTime());
//            order.setOrderState(OrderEnum.PENDING_PAY);
            order.setDestTime(new Timestamp(System.currentTimeMillis()));

            String orderJson = JsonUtil.toString(order);
            strRedisTemplate.opsForHash()
                    .put(OrderEnum.ORDERS_ING, order.getOrderNo(), orderJson);
        }
    }
}